package org.pub.fast.jdbc.page;

public class MSSQLLimitSQLBuilder implements LimitSQLBuilder {
	public String build(String sql, int pageIndex, int pageSize) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("select * from(");
		buffer.append(getRowSql(sql));
		buffer.append(")a where row >" + (pageIndex - 1) * pageSize
				+ " and row<=" + (pageIndex) * pageSize);
		return buffer.toString();
	}

	private Object getRowSql(String sql) {
		sql = sql.toLowerCase();
		int index = sql.indexOf("from");
		String frontSql = sql.substring(0, index);
		String endSql = sql.substring(index, sql.length());
		StringBuffer buffer=new StringBuffer();
		String row = "row=row_number() over(order by 1)";
		buffer.append(frontSql);
		buffer.append(",").append(row).append(" ");
		buffer.append(endSql);
		// TODO Auto-generated method stub
		return buffer.toString();
	}

	public static void main(String[] args) {
		MSSQLLimitSQLBuilder builder = new MSSQLLimitSQLBuilder();
		String s = builder.build("select * from bd_deptdoc", 2, 10);
		System.out.println(" " + s);
	}
}
